package algorithm;

import java.util.HashMap;
import java.util.PriorityQueue;

public class Letter {
    public static void main(String[] args) {
        String s = "world";
        String t = "rdlo";
        //System.out.println(letterXOR(s,t));
        // String words = "how are you";
        // System.out.println(reverseWords(words));
        String words = "abbcccdffe";
        System.out.println(sortByWords(words));
    }

    public static boolean letterXOR(String s,String t) {
        if (s == null || t == null || s.length() != t.length()) {
            return false;
        }
        int[] nums = new int[26];
        for (int i = 0; i < s.length(); i++) {
            nums[s.charAt(i) - 'a']++; // nums[25] = 1
            nums[t.charAt(i) - 'a']--;// nums[20] = -1
        }
        for (int num : nums) {
            if (num != 0) {
                return false;
            }
        }
        return true;
    }

    // how are you
    public static String reverseWords(String words) {
        int i = words.length() - 1;
        StringBuilder sb = new StringBuilder();
        int end = words.length();
        while (i > 0) {
            i--;
            // 从后向前，依次拼接单个单词
            if (words.charAt(i) == ' ') {
                sb.append(words, i+1, end).append(' ');
                end = i;
            }
        }
        // 拼接第一段单词
        sb.append(words, 0, end);
        return sb.toString();
    }

    // 按照字母出现频率对单词排序
    public static String sortByWords(String words){
        // map存放字符和它出现的次数
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < words.length(); i++) {
            char c = words.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        PriorityQueue<Character> queue = new PriorityQueue<>((o1, o2) -> {
            // 按照字母出现的次数倒序排列
            return map.get(o2) - map.get(o1);
        });
        queue.addAll(map.keySet());
        StringBuilder sb = new StringBuilder();
        while (queue.size() > 0) {
            Character ch = queue.remove();
            for (int i = 0; i < map.get(ch); i++) {
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}
